package net.tv90.auth.service.impl;

import net.tv90.auth.model.Mail;
import net.tv90.auth.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class SendMailServiceImpl implements SendMailService {

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Value("${spring.application.name}")
    private String name;

    @Value("${spring.mail.addr}")
    private String addr;

    @Override
    public void sendCodeMailTo(String email, String code) {
        Mail mail = new Mail(
                addr + "(" + name + ")",
                email,
                code + " 是你的验证码",
                "【" + name + "】验证码：" + code + "。验证码提供他人可能导致账号被盗，请勿转发或泄漏。"
        );
        jmsMessagingTemplate.convertAndSend("mail.queue", mail);
    }

    @Override
    public void sendIdentifyMailTo(String email, String username) {
        Mail mail = new Mail(
                addr + "(" + name + ")",
                email,
                "身份验证提醒",
                "用户" + username + "，你的身份验证已经完成。如非本人操作，请立即修改密码。"
        );
        jmsMessagingTemplate.convertAndSend("mail.queue", mail);
    }

    @JmsListener(destination = "mail.queue")
    public void sendCodeMailListener(Mail mail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(mail.getFrom());
        mailMessage.setTo(mail.getTo());
        mailMessage.setSubject(mail.getTitle());
        mailMessage.setText(mail.getText());
        mailSender.send(mailMessage);
    }
}
